package cn.tedu.knows.portal.service.impl;

import cn.tedu.knows.portal.exception.ServiceException;
import cn.tedu.knows.portal.mapper.UserMapper;
import cn.tedu.knows.portal.model.Comment;
import cn.tedu.knows.portal.mapper.CommentMapper;
import cn.tedu.knows.portal.model.User;
import cn.tedu.knows.portal.service.ICommentService;
import cn.tedu.knows.portal.vo.CommentVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.yaml.snakeyaml.events.Event;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2021-11-26
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {
@Autowired
private CommentMapper commentMapper;
@Autowired
private UserMapper userMapper;
    @Override
    @Transactional
    public Comment saveComment(CommentVO commentVO, String username) {
        User user=userMapper.findUserByUsername(username);
        Comment comment=new Comment()
                .setUserId(user.getId())
                .setUserNickName(user.getNickname())
                .setAnswerId(commentVO.getAnswerId())
                .setContent(commentVO.getContent())
                .setCreatetime(LocalDateTime.now());
        int num=commentMapper.insert(comment);
        if (num!=1){
            throw new ServiceException("数据库忙");
        }
        return comment;
    }

    @Override
    public boolean removeComment(Integer commentId, String username) {
        User user=userMapper.findUserByUsername(username);
        if (user.getType().equals(1)){
            //如果当前是讲师,能够删除任何评论
            int num=commentMapper.deleteById(commentId);
            return num==1;
        }
        // 不是讲师删除评论要判断当前登录用户是不是评论的发布者
        // 而要想获得评论发布者的id,需要先按评论id查询评论对象
        Comment comment=commentMapper.selectById(commentId);
        if (user.getId().equals(comment.getUserId())){
            // 如果删除评论的用户是评论的发布者
            int num=commentMapper.deleteById(commentId);
            return num==1;
        }
        throw new ServiceException("你无权删除别人的评论 滚!");
    }
}
